package com.tuozixuan.exchanger;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ExchangerTimeoutDemo {

	public static void main(String[] args) {
		ExecutorService executorService = Executors.newFixedThreadPool(2);
		
	    final Exchanger<String> exchanger = new Exchanger<>();
		executorService.execute(() -> {
			
			try {
				String data =  "小明的苹果";
				String exchangeData = (String)exchanger.exchange(data, 3, TimeUnit.SECONDS);
				System.out.println("小明交换得到的数据：" + exchangeData);
			} catch (InterruptedException | TimeoutException e) {
				e.printStackTrace();
			}
		});
		
		executorService.execute(() -> {
			
			try {
				String data =  "小刚的苹果";
				Thread.sleep(5000);
				String exchangeData = (String)exchanger.exchange(data, 3, TimeUnit.SECONDS);
				System.out.println("小刚交换得到的数据：" + exchangeData);
			} catch (InterruptedException | TimeoutException e) {
				e.printStackTrace();
			}
		});
		
		executorService.shutdown();
	}

}
